<?php

namespace app\m\controller;

use think\Db;

/**
 * Class We 微信基础类
 * @package app\m\controller
 */
class WeBase
{
    protected $appId = 'wx55028414c0107b91';

    private $appSecret = '78fdf5d78adcdb3953311a3acb088b52';

    protected $appToken = 'deXm98mYeQ';

    protected function getToken()
    {
        $token = cache('xzb_token');
        if (!empty($token))
            return $token;
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->appId . '&secret=' . $this->appSecret;
        $result = curl($url);
        $json = json_decode($result, true);
        if (empty($json) || isset($json['error'])) {
            return false;
        } else {
            cache('xzb_token', $json['access_token'], $json['expires_in'] - 100);
            return $json['access_token'];
        }
    }

    protected function getAuthUrl($url, $type = 1, $state = 'wxm')
    {
        // $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->appId . '&redirect_uri=' . urlencode($url) . '&response_type=code&scope=' . ($type == 1 ? 'snsapi_base' : 'snsapi_userinfo') . '&state=' . $state . '&component_appid=' . $this->appId . '#wechat_redirect';
        // return $url;
        return 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->appId . '&redirect_uri=' . urlencode($url) . '&response_type=code&scope=' . ($type == 1 ? 'snsapi_base' : 'snsapi_userinfo') . '&state=' . $state . '#wechat_redirect';
    }

    private function get_jsapi_ticket()
    {
        $ticket = cache('xzb_ticket');
        if (!empty($ticket))
            return $ticket;
        $token = $this->getToken();
        if (!$token)
            return false;
        $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' . $token . '&type=jsapi';
        $result = curl($url);
        $json = json_decode($result, true);
        if (empty($json) || $json['errcode'] != '0') {
            return false;
        } else {
            cache('xzb_ticket', $json['ticket'], $json['expires_in'] - 100);
            return $json['ticket'];
        }
    }

    protected function getUserInfo($openID)
    {
        $token = $this->getToken();
        if (!$token)
            return false;
        $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $token . '&openid=' . $openID . '&lang=zh_CN';
        $result = curl($url);
        loger($result,'wx_user');
        $user = json_decode($result, true);
        if ($user && $user['subscribe'] == '1')
            return $user;
        else
            return false;
    }

    protected function getAuthToken($code)
    {
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this->appId . '&secret=' . $this->appSecret . '&code=' . $code . '&grant_type=authorization_code';
        $result = curl($url);
        $json = json_decode($result, true);
        return $json;
    }

    protected function responseText($fromUserName, $toUserName, $time, $content)
    {
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    </xml>";
        $msgType = "text";
        $str = sprintf($textTpl, $toUserName, $fromUserName, $time, $msgType, $content);
        echo $str;
    }

    /**
     * 获取用户基本信息，不需要关注公众号
     * @param $openid
     * @param $token
     * @return bool|mixed
     */
    protected function wx_userinfo($openid, $token)
    {
        // https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $token . '&openid=' . $openid . '&lang=zh_CN';
        $result = curl($url);
        // loger($token . '   ' . $result, 'user');
        $user = json_decode($result, true);
        if ($user)
            return $user;
        else
            return false;
    }

    /**
     * @param $url 要跳转的url
     * @return  ses 对象, false 直接跳转到授权页面
     * @throws \think\Exception
     */
    protected function wx_auth($url)
    {
        $ses = session('ses');
        if ($ses) {
            return $ses;
        }

        if (isset($_GET['code'])) {
            $token = $this->getAuthToken($_GET['code']);
            if (!$token || isset($token['errcode'])) {
                print_r($token);
                return;
            }
            $openid = $token['openid'];
            $qs = Db::query('select id as oid,nickname,headimgurl,subscribe from wx_auth where openid=?', [$openid]);
            if ($qs) {
                $ses = $qs[0];

            } else {

                $user = $this->wx_userinfo($openid, $token['access_token']);
                $oid = Db::table('wx_auth')->insertGetId($user);

                $user['oid'] = $oid;

                $ses = ['oid' => $oid, 'nickname' => $user['nickname'], 'headimgurl' => $user['headimgurl']];
            }

            if ($ses) {
                session('ses', $ses);
                $view = new \think\View();
                echo $view->fetch('/jump', ['url' => $url]);
                return null;
            }
        }
        // 跳转到授权页面
        $url = $this->getAuthUrl($url, 2);
        header('Location:' . $url);
        return null;
    }


}
